/*
 * Pressure_Sensor.c
 *
 * Created: 1/23/2013 2:24:18 PM
 *  Author: Parag
 */ 



#include "Pressure_Sensor.h"


/************************************
* Method:		Pressure_Init
* FullName:		Pressure_Init
* Access:		public 
* Returns:		void
* Qualifier:	
* Parameter:	void
* Description:	
************************************/
void Pressure_Init(void)
{

	PressureDDR	|= (1<<P_Pressure);		//Pressure Chip select output
	PressurePort |= (1<<P_Pressure);	// set output high/Chip Disable
}

void Pressure_Get(uint16_t * output)
{
	uint8_t high,low;
	
	
	
	Pressure_PIN |= (1<<P_Pressure);							// CS enables / replace this with appropriate POUT

	high = ReadByteSPI(0xFF);
	low = ReadByteSPI(0xFF);
	
	Pressure_PIN |= (1<<P_Pressure);							// CS disable
	
	*output = ((high<<8) | low);
}

PS_Status Pressure_Get_Status(uint16_t * output)
{
	uint16_t status = *output;
		
	(status>>=14);
	*output &= 0b0011111111111111;								// or *output &= ~(0b11<<14) or *output &= ~(3<<14)
	return (PS_Status)status;
}

bool Pressure_Data_Okay(PS_Status status)
{
	static int staleData = 0;
	
	switch(status)
	{	
		case Good_Data: 
			return true;
			
		case Command_Mode:
			return false;
			
		case Stale_Data:
		{
			staleData++;
					
			// too many stale datas
			if(staleData == allowedAmountOfStaleData)
			{
				staleData = 0;
				return false;
			}
			// I will let it go unless this happens an allowedAmountofStaleData amount of times
			return true;
		}
		
		case Malfunction:
			return false;
			
		default:
			return false;
	}			
}

bool Pressure_Read_Sensor(uint16_t *output)
{
	Pressure_Get(output);
	return Pressure_Data_Okay( Pressure_Get_Status(output) );
}